package oss.ngocminh.fw.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import oss.ngocminh.fw.data.Subscription;

public class SubscriptionDAO {
	
	private static final String ID = "_ID";
	public static final String THREAD_ID = "thread_id";
	public static final String LAST_READ_POST_ID = "last_read_post_id";
	public static final String PASSWORD = "password";
	public static final String USER_NAME = "user_name";
	public static final String TABLE_NAME = "subscription";
	
	private DatabaseHelper db;
	private ThreadDAO threadDAO;
	
	public SubscriptionDAO(DatabaseHelper db) {
		super();
		this.db = db;
		threadDAO = new ThreadDAO(db);
	}

	public void saveOrUpdate(Subscription sub) {
		if (sub.getId() == null) {
			save(sub);
		} else {
			update(sub);
		}
	}

	public void update(Subscription sub) {
		ContentValues cv = new ContentValues();
		cv.put(USER_NAME, sub.getUserName());
		cv.put(PASSWORD, sub.getPassword());
		cv.put(LAST_READ_POST_ID, sub.getLastReadPostId());
		cv.put(THREAD_ID, sub.getThread().getId());
		db.getWritableDatabase().update(TABLE_NAME, cv, 
				ID + "=?", new String[] {String.valueOf(sub.getId())});
	}

	public void save(Subscription sub) {
		ContentValues cv = new ContentValues();
		cv.put(USER_NAME, sub.getUserName());
		cv.put(PASSWORD, sub.getPassword());
		cv.put(LAST_READ_POST_ID, sub.getLastReadPostId());
		cv.put(THREAD_ID, sub.getThread().getId());
		long id = db.getWritableDatabase().insert(TABLE_NAME, "", cv);
		sub.setId(id);
	}
	
	public List<Subscription> list() {
		Cursor result = db.getReadableDatabase().query(TABLE_NAME,
				new String[] {ID, USER_NAME, PASSWORD, LAST_READ_POST_ID, THREAD_ID }, 
				"", null, null, null, null);
		List<Subscription> subs = toSubscriptions(result);
		result.close();
		return subs;
	}

	private List<Subscription> toSubscriptions(Cursor result) {
		List<Subscription> subs = new ArrayList<Subscription>();
		while (result.moveToNext()) {
			subs.add(new Subscription(result.getLong(0), result.getString(1),
					result.getString(2), threadDAO.findById(result.getInt(4)), 
					result.getString(3)));
		}
		return subs;
	}
	
}
